package com.web.handler;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.web.dao.UserMapper;
import com.web.domain.MRole;
import com.web.domain.MUser;
import com.web.entity.User;
import com.web.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xukk
 * @date 2017/6/5
 */
@Slf4j
@Service
public class CustomUserService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<User> userList = userMapper.selectByUserNameOrPhone(s);
        if (userList.size() == 0 || userList == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        if (userList.size() > 1) {
            throw new UsernameNotFoundException("用户存在多个");
        }
        User user = userList.get(0);
        List<MRole> mRoles = Lists.newArrayList();
        roleService.getRoleDetail(user.getRoles());
        if (user.getRoles() != null) {
            user.getRoles().forEach(value -> {
                MRole mRole = new MRole();
                mRole.setRoleId("" + value.getId());
                mRole.setPermissions(Sets.newHashSet());
                mRole.setMenus(Sets.newHashSet());
                if (value.getPermissions() != null) {
                    value.getPermissions().forEach(v ->
                            mRole.getPermissions().add(v.getPerm())
                    );
                }
                if (value.getMenus() != null) {
                    value.getMenus().forEach(k -> {
                        if (StringUtils.isNotBlank(k.getUrl())) {
                            mRole.getMenus().add(k.getUrl());
                        }
                    });
                }
                mRoles.add(mRole);
            });
        }
        MUser authUser = new MUser(user.getId(), user.getUsername(), user.getPassword(),
                mRoles, user.getAccountNonExpired(), user.getCredentialsNonExpired(),
                user.getAccountNonLocked(), user.getEnabled());
        return authUser;

    }
}
